<script setup>
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import { message } from 'ant-design-vue'
	import { watch, ref, computed, shallowRef } from 'vue'
	import MySQLConnectorForm from './mysql/MySQLConnectorForm.vue'
	import HttpConnectorForm from './http/HTTPConnectorForm.vue'
	import XiaoNuoConnectorForm from './xiaonuo/XiaoNuoConnectorForm.vue'
	import LocalAPIConnectorForm from './LocalAPIConnectorForm.vue'
	import ExternalAPIConnectorForm from './ExternalAPIConnectorForm.vue'

	const title = computed(() => (formData.value.id ? '修改数据连接器' : '添加数据连接器'))

	const emit = defineEmits(['success'])
	// 抽屉是否可见
	const visible = ref(false)

	// 表单对象
	const formData = ref({
		name: '',
		type: 'MYSQL',
		description: '',
		config: {
			params: 'useSSL=false&serverTimezone=Asia/Shanghai',
			url: ''
		}
	})

	// 表单规则
	const rules = {
		name: [{ required: true, message: '请输入连接器名称' }],
		type: [{ required: true, message: '请选择连接器类型' }],
		config: [{ required: true, message: '请完善连接配置信息' }]
	}

	// 表单引用
	const formRef = ref()
	// 子表单引用
	const connectorFormRef = ref()

	// 监听配置变化
	const handleConfigChange = (newConfig) => {
		formData.value.config = newConfig
	}

	// 监听类型变化
	const handleTypeChange = (value) => {
		// 更新配置
		switch (value) {
			case 'MYSQL':
				formData.value.config = {
					params: 'useSSL=false&serverTimezone=Asia/Shanghai',
					url: ''
				}
				currentConnectorForm.value = MySQLConnectorForm
				break
			case 'HTTP':
				formData.value.config = {}
				currentConnectorForm.value = HttpConnectorForm
				break
			case 'XIAONUO':
				formData.value.config = {}
				currentConnectorForm.value = XiaoNuoConnectorForm
				break
			case 'LOCAL_API':
				formData.value.config = {
					scanModules: JSON.stringify(['dashboard', 'sys']),
					onlyGetMethods: 'true',
					enablePermissionCheck: 'true',
					excludeSystemApis: 'true',
					excludePaths: JSON.stringify([]),
					cacheTimeout: '300',
					enableCache: 'true'
				}
				currentConnectorForm.value = LocalAPIConnectorForm
				break
			case 'EXTERNAL_API':
				formData.value.config = {
					baseUrl: '',
					authType: 'BEARER_TOKEN',
					timeout: '30000',
					retryCount: '3',
					auth_token: '',
					auth_prefix: 'Bearer ',
					apis: JSON.stringify([])
				}
				currentConnectorForm.value = ExternalAPIConnectorForm
				break
			default:
				formData.value.config = {}
				currentConnectorForm.value = null
		}
	}

	// 提交表单
	const onSubmit = async () => {
		try {
			// 校验主表单
			await formRef.value.validate()
			// 校验子表单
			if (connectorFormRef.value?.validate) {
				await connectorFormRef.value.validate()
			}

			// 准备提交数据，直接使用config配置
			const submitData = {
				...formData.value,
				...formData.value.config
			}

			console.log('提交数据:', submitData)

			// 提交数据
			await dataConnectorApi.add(submitData)
			message.success('保存成功')
			onClose()
			emit('success')
		} catch (error) {
			console.error('表单校验失败:', error)
		}
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		resetForm()
	}

	// 重置表单
	const resetForm = () => {
		// 重置主表单
		formRef.value?.resetFields()
		// 重置子表单
		if (connectorFormRef.value?.resetFields) {
			connectorFormRef.value.resetFields()
		}
		formData.value = {
			name: '',
			type: 'MYSQL',
			description: '',
			config: {
				params: 'useSSL=false&serverTimezone=Asia/Shanghai',
				url: ''
			}
		}
	}

	// 当前连接器表单组件
	const currentConnectorForm = shallowRef(null)

	// 监听类型变化更新表单组件
	watch(
		() => formData.value.type,
		(type) => {
			console.log('当前连接器类型:', type)
			switch (type) {
				case 'MYSQL':
					currentConnectorForm.value = MySQLConnectorForm
					break
				case 'HTTP':
					currentConnectorForm.value = HttpConnectorForm
					break
				case 'XIAONUO':
					currentConnectorForm.value = XiaoNuoConnectorForm
					break
				case 'LOCAL_API':
					currentConnectorForm.value = LocalAPIConnectorForm
					break
				case 'EXTERNAL_API':
					currentConnectorForm.value = ExternalAPIConnectorForm
					break
				default:
					currentConnectorForm.value = null
			}
		}
	)
	const open = (data) => {
		// 重置表单
		resetForm()
		// 如果传入了数据，则更新表单
		if (data) {
			// 先触发类型变更以初始化对应的表单组件
			handleTypeChange(data.type)

			// 直接使用传入的config数据，不再处理嵌套结构
			const processedConfig = data.config || {}

			// 更新表单数据
			formData.value = {
				...formData.value,
				...data,
				config: processedConfig
			}
		} else {
			// 新增时初始化为MySQL类型
			handleTypeChange('MYSQL')
		}
		// 打开抽屉
		visible.value = true
	}
	defineExpose({
		open
	})
</script>

<template>
	<a-drawer :title="title" :width="'50%'" :open="visible" @close="onClose">
		<a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
			<a-form-item label="连接器名称" name="name">
				<a-input v-model:value="formData.name" placeholder="请输入连接器名称" />
			</a-form-item>
			<a-form-item label="连接器类型" name="type">
				<a-select v-model:value="formData.type" placeholder="请选择连接器类型" @change="handleTypeChange">
					<a-select-option value="MYSQL">MySQL</a-select-option>
					<a-select-option value="LOCAL_API">本地API</a-select-option>
					<a-select-option value="EXTERNAL_API">外部API</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="连接器描述" name="description">
				<a-textarea v-model:value="formData.description" placeholder="请输入连接器描述" :rows="4" />
			</a-form-item>
		</a-form>
		<a-divider>连接配置</a-divider>
		<component
			:is="currentConnectorForm"
			ref="connectorFormRef"
			:modelValue="formData.config"
			@change="handleConfigChange"
		/>
		<template #footer>
			<div class="flex justify-end">
				<a-space>
					<a-button @click="onClose">取消</a-button>
					<a-button type="primary" @click="onSubmit">确定</a-button>
				</a-space>
			</div>
		</template>
	</a-drawer>
</template>
